package com.tql.mall.product.controller;


import com.tql.mall.common.result.R;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;


/**
 * @Author: tyk
 * @Date: 2023/5/22 13:35
 * @Description: 上传文件到Minio
 */
@RestController
@RequestMapping("/admin/product/fileUpload")
@Api(description = "文件上传")
public class FileUploadController {

    //  获取文件上传对应的地址
    @Value("${minio.endpointUrl}")
    public String endpointUrl;

    @Value("${minio.accessKey}")
    public String accessKey;

    @Value("${minio.secretKey}")
    public String secretKey;

    @Value("${minio.bucketName}")
    public String bucketName;

    /**
     * 上传图片到Minio
     */
    @PostMapping("img")
    @ApiOperation("上传图片到Minio")
    public R<String> imgUpload(@ApiParam("图片文件") MultipartFile file) {
        return fillUpload(file, bucketName);
    }

    /**
     * 上传文件到Minio
     */
    private R<String> fillUpload(MultipartFile file, String bucketName) {
        String url;
        try {
            // 创建Minio客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpointUrl)
                    .credentials(accessKey, secretKey)
                    .build();
            // 检查桶是否存在
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isExist) minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
            //  文件名
            String fileName = System.currentTimeMillis() + UUID.randomUUID().toString();
            // 上传文件
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                            file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );
            // 拼接访问路径
            url = endpointUrl + "/" + bucketName + "/" + fileName;
        } catch (Exception e) {
            url = "";
        }
        // 返回文件路径
        return R.ok(url);
    }
}
